<template>
  <div>
    <div class="serch-result-container">
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    offset="50"
    :immediate-check="false"
    >
     <ArtItem :artcle='obj' v-for="(obj) in searchList" :key="obj.art_id" :isShow='false' @click.native="itemClickFn(obj.art_id)"></ArtItem>
    </van-list>
  </div>
</template>

<script>
import ArtItem from '@/components/ArtItem'
import { searchResultAPI } from '@/api'
export default {
  name: 'SearchResult',
  components: { ArtItem },
  data () {
    return {
      page: '1', // 页数
      per_page: '10', // 每页数量
      searchList: [], // 搜索文章的列表
      loading: false,
      finished: false
    }
  },
  created () {
    this.getData()
  },
  methods: {
    // 获取搜索结果数据
    async getData (pages = 1) {
      const q = this.$route.params.kw
      this.page = pages
      try {
        const res = await searchResultAPI({
          page: this.page,
          per_page: this.per_page,
          q
        })
        this.searchList = [...this.searchList, ...res.data.data.results]
        this.loading = false
        if (res.data.data.results.length === 0) { // 按理说，后端会给一个字段，代表数据已经全部加载完了。但是他没给
        // 遇到这种情况，我们就去网络请求那里看，当数据没有后，results就为空数组，我们可以利用这个来判断
          this.finished = true
        }
      } catch (error) {

      }
    },
    // 列表滚动加载更多
    onLoad () {
      if (this.searchList.length > 0) {
        this.page++
        this.getData(this.page)
      }
    },
    // 获取文章详情
    itemClickFn (art_id) {
      this.$router.push({
        path: '/detail',
        query: {
          art_id: art_id
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.serch-result-container {
  padding-top: 46px;
}
</style>
